import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { Form, Input, Row, Button, message } from 'antd'
import { UserOutlined, UnlockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons'
import { connect } from 'react-redux'
import { login, getUserInfo } from '@/store/actions'

import './login.scss'

class Login extends Component {

  handleLogin = (username, password) => {
    login(username, password)
      .then((data) => {
        message.success('登录成功')
        this.handleUserInfo(data.token)
        this.props.history.push('/')
      })
      .catch((error) => {
        message.error(error)
      })
  }

  handleUserInfo = (token) => {
    getUserInfo(token)
      .then((data) => {})
      .catch((error) => {
        message.error(error)
      })
  }

  onFinish = (values) => {
    const { username, password } = values
    this.handleLogin(username, password)
  }

  render() {
    return (
      <div className="app-login">
        <Form 
        className="app-login-form" 
        layout="horizontal" 
        onFinish={this.onFinish}
        initialValues={{
          username: 'admin',
          password: 'admin'
        }}
      >
          <h1>后台管理系统</h1>
          <Form.Item name="username" rules={[{ required: true }]} hasFeedback>
            <Input size="large" autoComplete="off" prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true }]} hasFeedback>
            <Input.Password autoComplete="off" size="large" prefix={<UnlockOutlined />} placeholder="密码" iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)} />
          </Form.Item>
          <Row>
            <Button block={true} size="large" type="primary" htmlType="submit">登录</Button>
          </Row>
        </Form>
      </div>
    )
  }
}

export default withRouter(connect(state => state.user, { login, getUserInfo })(Login))
